#include "DrvUART010.h"
#include "io.h"
#include "unione_lite.h"
#include "pwm.h"
#include "gpio.h"

ASRC_PWM_REG *asrc_pwm_reg_ptr = (ASRC_PWM_REG*)PWM_UNIPWM_PA_BASE;

void pwm_register_dump()
{
	fLib_printf("ASRC_MODE = 0x%08X\n", *(UINT32*)&asrc_pwm_reg_ptr->ASRC_MODE);
	fLib_printf("ASRC_BYPASS = 0x%08X\n", *(UINT32*)&asrc_pwm_reg_ptr->ASRC_BYPASS);
	fLib_printf("ASRC_OFFSET = 0x%08X\n", *(UINT32*)&asrc_pwm_reg_ptr->ASRC_OFFSET);
	fLib_printf("ASRC_OUT_SAMPL_RATE = 0x%08X\n", *(UINT32*)&asrc_pwm_reg_ptr->ASRC_OUT_SAMPL_RATE);
	fLib_printf("ASRC_IN_SAMPL_RATE = 0x%08X\n", *(UINT32*)&asrc_pwm_reg_ptr->ASRC_IN_SAMPL_RATE);
	fLib_printf("ASRC_RADIO_RATE_CFG = 0x%08X\n", *(UINT32*)&asrc_pwm_reg_ptr->ASRC_RADIO_RATE_CFG);
	fLib_printf("ASRC_LOCK = 0x%08X\n", *(UINT32*)&asrc_pwm_reg_ptr->ASRC_LOCK);

	fLib_printf("PWM_MODE = 0x%08X\n", *(UINT32*)&asrc_pwm_reg_ptr->PWM_MODE);
	fLib_printf("PWM_CNT_CONFIG = 0x%08X\n", *(UINT32*)&asrc_pwm_reg_ptr->PWM_CNT_CONFIG);
	fLib_printf("PWM_OP_ENABLE = 0x%08X\n", *(UINT32*)&asrc_pwm_reg_ptr->PWM_OP_ENABLE);

	fLib_printf("FIFO_STATUS = 0x%08X\n", *(UINT32*)&asrc_pwm_reg_ptr->FIFO_STATUS);
	fLib_printf("PWM_ERROR_CNT = 0x%08X\n", *(UINT32*)&asrc_pwm_reg_ptr->PWM_ERROR_CNT);

}

void enable_pwm_play(void)
{
	UINT32 RegVal;
    //disable pwm function
    RegVal = *(UINT32*)&asrc_pwm_reg_ptr->PWM_MODE;
	RegVal &= ~PWM_FUNC_BYPASS;
	*(UINT32*)&asrc_pwm_reg_ptr->PWM_MODE = RegVal;
	
	*(UINT32*)&asrc_pwm_reg_ptr->PWM_OP_ENABLE = PWM_REG_OP_ENABLE;
}

void disable_pwm_play(void)
{
	UINT32 RegVal;
	//enable pwm function
	RegVal = *(UINT32*)&asrc_pwm_reg_ptr->PWM_MODE;
	RegVal |= PWM_FUNC_BYPASS;
	*(UINT32*)&asrc_pwm_reg_ptr->PWM_MODE = RegVal;
	
	*(UINT32*)&asrc_pwm_reg_ptr->PWM_OP_ENABLE = PWM_REG_OP_ENABLE;
}

void pwm_module_init(void)
{
	UINT32 RegVal;

	//reset PWM module
	RegVal = READ(SCU_IP_RESET);
	RegVal &= ~SCU_IP_RESET_PWM;//reset PWM
	WRITE(SCU_IP_RESET, RegVal);
	RegVal = READ(SCU_IP_RESET);
	RegVal |= SCU_IP_RESET_PWM; //release the PWM reset signal
	WRITE(SCU_IP_RESET, RegVal);
	//configure ASRC into resample-only(bypass pwm func) mode
	*(UINT32*)&asrc_pwm_reg_ptr->ASRC_MODE = ASRC_RX_FIFO_BYPASS | ASRC_SINGLE_CHANNEL;
	*(UINT32*)&asrc_pwm_reg_ptr->ASRC_BYPASS  = ASRC_FUNC_BYPASS;
	*(UINT32*)&asrc_pwm_reg_ptr->ASRC_OFFSET   = ASRC_OFFSET_CFG;
	*(UINT32*)&asrc_pwm_reg_ptr->ASRC_OUT_SAMPL_RATE  = SAMPLE_RATE_16K * RATE_MULTI_PARAM;
	*(UINT32*)&asrc_pwm_reg_ptr->ASRC_IN_SAMPL_RATE   = SAMPLE_RATE_16K * RATE_MULTI_PARAM;
	*(UINT32*)&asrc_pwm_reg_ptr->ASRC_RADIO_RATE_CFG	= ASRC_RADIO_RATE;

	*(UINT32*)&asrc_pwm_reg_ptr->PWM_MODE = PWM_FUNC_BYPASS | PWM_INTERPOLATION_MODE | PWM_CLK_SEL_135168KHZ | PWM_INTERPOLATION_OUTPUT_16K;
	*(UINT32*)&asrc_pwm_reg_ptr->PWM_CNT_CONFIG = PWM_WORK_CLK/SAMPLE_RATE_16K;

	*(UINT32*)&asrc_pwm_reg_ptr->PWM_OP_ENABLE = PWM_REG_OP_ENABLE;

	enable_pwm_play();
	//pwm_register_dump();
}
